//
//  CTPhotoBrowser+Extension.swift
//  CTPhotoBrowser
//
//  Created by Andney Jack on 2021/2/26.
//

import Kingfisher
import UIKit

extension CTPhotoBrowser {
    /// 默认提供的加载图片方法
    /// - Parameters:
    ///   - itemView: 图片显示控件
    ///   - imageObj: 图片对象
    /// - Returns: 是否已处理好图片的加载逻辑
    @discardableResult
    public class func loadImage(itemView: CTPhotoBrowserItemView, imageObj: Any?, placeholder: UIImage?) -> Bool {
        itemView.didFetchImage = false
        itemView.removeIndicatorView()

        if imageObj == nil {
            itemView.imageView.image = placeholder
            return true
        }

        var networkUrl: URL?

        if let path = imageObj as? String {
            if path.hasPrefix("http") {
                // 网络图片
                if let url = URL(string: path) {
                    networkUrl = url
                } else {
                    if let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                        networkUrl = URL(string: encodedPath)
                    } else {
                        itemView.imageView.image = placeholder
                        return true
                    }
                }
            } else {
//                [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:fileType]]

                if let img = UIImage(named: path) {
                    itemView.imageView.image = img
                    itemView.didFetchImage = true
                } else if let img = UIImage(contentsOfFile: path) {
                    itemView.imageView.image = img
                    itemView.didFetchImage = true
                } else {
                    itemView.imageView.image = placeholder
                }

                return true
            }
        } else if let url = imageObj as? URL {
            networkUrl = url
        } else if let image = imageObj as? UIImage {
            itemView.imageView.image = image
            itemView.didFetchImage = true
            return true
        } else {
            // 未知的图片对象，需要外部进行处理
            return false
        }

        if itemView.isShowed {
            itemView.addIndicatorView()
        }

        itemView.imageView.kf.setImage(with: networkUrl, placeholder: placeholder) { [weak itemView] receivedSize, totalSize in
            guard let view = itemView, view.isShowed else {
                return
            }

            if totalSize > 0 {
                view.setIndicatorProgress(CGFloat(receivedSize) / CGFloat(totalSize))
            } else {
                view.setIndicatorProgress(0)
            }

        } completionHandler: { [weak itemView] result in
            itemView?.removeIndicatorView()

            switch result {
            case .success:
                itemView?.didFetchImage = true
            case .failure:
                itemView?.imageView.image = placeholder
            }
        }

        return true
    }
}
